package com.trimps.steps.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hotfire.template.common.Constants;
import com.hotfire.template.common.Paginator;
import com.trimps.steps.exception.LoginException;
import com.trimps.steps.exception.SqlOperationsException;
import com.trimps.steps.pojo.User;
import com.trimps.steps.pojo.WalkerGroup;
import com.trimps.steps.service.IUserService;
import com.trimps.steps.service.IUserWalkerGroupService;
import com.trimps.steps.service.IWalkerGroupService;

@Controller
@RequestMapping(value = "user/")
public class UserController extends BaseController {
    private static final Logger logger = Logger.getLogger(UserController.class);

    @Autowired
    private IUserService        userService;
    @Autowired
    private IWalkerGroupService walkerGroupService;
    @Autowired
    private IUserWalkerGroupService userWalkerGroupService;

    @RequestMapping(value = "doLogin")
    public String doLogin(@RequestParam(value = "username") String username,
                    @RequestParam(value = "password") String password,
                    @RequestParam(value = "referer", required = false) String referer,
                    ModelMap map,
                    HttpSession session) {
        try {
            User user = userService.login(username, password);
            if (user == null) {
                map.addAttribute("msg", "用户名或密码错误！");
                return "user/login";
            }
            session.setAttribute(Constants.USER_SESSION_ATTR, user);
        } catch (LoginException e) {
            logger.info("login exception = " + e.getMessage());
            map.addAttribute("msg", e.getMessage());
            return "user/login";
        }
        User user = getUser();
        Date lastTime = user.getLastLoginTime();
        String lastIp = user.getLoginIp();
        user.setLastLoginTime(new Date());
        user.setLoginIp(request.getRemoteAddr());
        userService.update(user);
        user.setLastLoginTime(lastTime);
        user.setLoginIp(lastIp);
        
        logger.info("next = " + referer);
        if(StringUtils.isEmpty(referer) || referer.equals("null")){
            return "redirect:/";
        }
        return "redirect:".concat(referer);
    }

    @RequestMapping(value = "logout")
    public String logout(HttpSession session) {
        Integer userId = getUserId();
        if(userId != null){
            session.removeAttribute(Constants.USER_SESSION_ATTR);
        }
        return "redirect:/";
    }

    /**
     * 获取用户列表
     * @param page  这里必须不能写@RequstParam注解，否则不能正常映射
     * @param map
     * @return
     */
    @RequestMapping(value = "list")
    public String userlist(Paginator page,
                    ModelMap map) {
        if(page == null || page.getTotalItemCount() == -1){
            page = new Paginator();
            page.setShowItemCount(8);
            int userCount = userService.getUserCount();
            page.setTotalItemCount(userCount);
        }
        List<User> users = userService.getAllUser(page.getStart(), page.getOffset());
        List<WalkerGroup> walkerGroups = walkerGroupService.getAllWalkerGroups();
        
        map.put("users", users);
        map.put("page", page);
        map.put("walkerGroups", walkerGroups);
        return "user/userlist";
    }
    

    @RequestMapping(value = "doSave")
    @ResponseBody
    public Map<String, Object> doSave(User user,
                    ModelMap modelMap) {
        try {
            int id = userService.save(user);
            if(id > 0){
                return super.buildSuccessMsg("保存成功！");
            } 
        } catch (SqlOperationsException e) {
            return super.buildFailureMsg(e.getMessage());
        }
        
        return super.buildFailureMsg("保存失败！");
    }
    
    
    @RequestMapping(value = "modifyPasswd")
    @ResponseBody
    public Map<String, Object> modifyPasswd(String oldPassword, String newPassword,HttpSession session, HttpServletResponse response ) {
        User user = getUser();
        if(!oldPassword.equals(user.getPassword()))
            return super.buildFailureMsg("密码错误！");
        user.setPassword(newPassword);
        userService.update(user);
        session.removeAttribute(Constants.USER_SESSION_ATTR);
        response.setHeader("Authorized", "false");
        return super.buildFailureMsg("保存成功！");
    }
    
    @RequestMapping(value = "doDel")
    public String del(HttpServletRequest request, 
                    @RequestParam(required=true) int id,
                    ModelMap modelMap) {
        int ret = userService.delById(id);
        if(ret <= 0){
            return super.sendErrorPage(request, "删除用户失败！");
        }
        return "redirect:list";
    }

    @ResponseBody
    @RequestMapping(value = "getWalkerGroupsByUserId")
    public List<WalkerGroup> getWalkerGroupsByUserId(@RequestParam(required=true) int userId ) {
        return userService.getWalkerGroupsById(userId);
    }
    
    @ResponseBody
    @RequestMapping(value = "saveUserWalkerGroup")
    public Map<String, Object> saveUserWalkerGroup(@RequestParam(required=true) int userId ,
                    @RequestParam(required=true) String groupIds ) {
        userWalkerGroupService.delByUserId(userId);
        int ret = userWalkerGroupService.saveUserWalkerGroup(userId, groupIds.split(","));
        
        if(ret > 0)
            return buildSuccessMsg("保存成功！");
        return buildFailureMsg("保存失败！");
    }
    
    @ResponseBody
    @RequestMapping(value = "saveWalkerGroup")
    public Map<String, Object> saveWalkerGroup(WalkerGroup walkerGroup) {
        int ret = walkerGroupService.save(walkerGroup);
        if(ret > 0)
            return buildSuccessMsg("保存成功！");
        return buildFailureMsg("保存失败！");
    }
    
    @RequestMapping(value = "doDelWalkerGroup")
    public String doDelWalkerGroup(@RequestParam(required=true) int groupId ) {
        int ret = walkerGroupService.delById(groupId);
        if(ret > 0)
            return "redirect:walkergrouplist";
        return sendErrorPage(request, "删除失败！");
    }
    
    @RequestMapping(value = "walkergrouplist")
    public String walkergrouplist(ModelMap modelMap) {
        List<WalkerGroup> walkerGroups = walkerGroupService.getAllWalkerGroups();
        modelMap.put("walkerGroups", walkerGroups);
        return "user/walkergrouplist";
    }
}
